<?php
namespace member\service;

use api\utils\PayApiClient;
use herosphp\core\Loader;
use herosphp\core\Log;


class MemberService extends CommonService {

    /**
     * 统计每组的会员数量
     * @param string|array $group_id
     * @return array|mixed
     */
    public function getCount( $group_id = null ){
        $conditions = array();
        $conditions['del_status'] = 0;
        if( is_array($group_id) ){
            $conditions['group_id']['$in'] = $group_id;
        }
        if( is_string($group_id)){
            $conditions['group_id']=$group_id;
        }
        return $this -> getModelDao() ->getItems($conditions,"count(*) as `total`,group_id","","","group_id","");
    }

    /**
     * 重写getItems，增加实名认证信息
     * @param array|string $conditions
     * @param array|string $fields
     * @param array|string $order
     * @param $limit
     * @param string $group
     * @param array|string $having
     * @return array|bool
     */
    public function getItems($conditions, $fields, $order, $limit, $group, $having)
    {

        $item = $this ->getMemberList($conditions, $fields, $order, $limit, $group, $having); // TODO: Change the autogenerated stub
        $dasu_pay_ids = array();
        foreach ($item as $key => $value){
            $value['total_cost'] = "---";
            if( !$value['real_name'] ){
                $value['real_name'] = "---";
            }
            $value['last_trade_time'] = "---";
            if( $value['dasu_pay_id'] ){
                $dasu_pay_ids[] = $value['dasu_pay_id'];
            }
            $tep[] = $value;
        }
        $items = $tep;
        if( !empty($dasu_pay_ids)) {
            $conditions = array('id' => array('$in' => $dasu_pay_ids));
            $url = "api/user/getUsersInfo";
            $params['conditions'] = $conditions;
            $params['fields'] = 'id,total_cost,usable,last_trade_time';
            $params['order'] = 'null';
            $params['page'] = '0';
            $params['pagesize'] = '2147483648';
            $result = PayApiClient::send($url, $params);
            if ($result->isSucess()) {
                $res = $result->getItems();
                foreach ($items as $key => $value) {
                    foreach ($res as $k => $v) {
                        if ($v['id'] == $value['dasu_pay_id']) {
                            $value['total_cost'] = $v['total_cost']?$v['total_cost']:'0.00';
                            $value['last_trade_time'] = $v['last_trade_time']?$v['last_trade_time']:'---';
                            $value['usable'] = $v['usable']?$v['usable']:'---';
                        }
                    }
                    $temp[] = $value;
                }
                $items = $temp;
                return $items;
            } else {
                Log::error("后台获取用户认证、累计消费失败，接口返回:".$result->getMessage());
                return false;
            }
        }else{
            return $items;
        }
        //var_dump($items);die;
    }

    /**
     * 重写getItems，增加会员组信息
     * @param $conditions
     * @param $fields
     * @param $order
     * @param $limit
     * @param $group
     * @param $having
     * @return array|mixed|null
     */
    public function getMemberList($conditions, $fields, $order, $limit, $group, $having)
    {
        if( !isset($conditions['del_status'])){
            $conditions['del_status'] = 0;
        }
        $items = parent::getItems($conditions, $fields, $order, $limit, $group, $having); // TODO: Change the autogenerated stub
        if( !$items )return null;
        $groupDao = Loader::model("memberGroup");
        $name = $groupDao -> getItems(array('status'=>1),"id,name","","","","");
        foreach ($items AS $value){
            $value['group_name'] = "无分组";

            foreach ($name as $v){
                if( $value['group_id'] == $v['id'] ){
                    $value['group_name'] = $v['name'];
                }
            }
            $temp[] = $value;
        }
        $items = $temp;
        return $items;
    }

    /**
     * override getItem 增加大塑支付信息,用于mpe后台编辑客户
     * @param array|string $condition
     * @param array|string $fields
     * @param array|string $order
     * @return array|bool|false|mixed
     */
    public function getItemWithSignInfo($condition, $fields, $order)
    {
        $item = parent::getItem($condition, $fields, $order);
        if( $item['dasu_pay_id'] ){
            $params = array(
                'userid' => $item['dasu_pay_id'],
                'fields' => "username as dasu_username,contacter as dasu_name,usable,sign_bank_id,balance,total_cost,card_no,virtual_account,payway,ischecked,sign_status,last_trade_time"
            );
            $result = PayApiClient::send('api/user/getUserInfo',$params);
            if( $result->isSucess() ){
                return $item+$result->getItem();
            }else{
                Log::error('编辑用户时，获取接口数据失败，接口返回：'.$result->getMessage());
                $item['dasu_pay_id'] = false;
                return $item;
            }
        }else{
            return $item;
        }
    }

    /**
     * override
     * @param $id
     * @return bool|int
     */
    public function delete($id)
    {
        return parent::update(array('del_status' => 1,'session_id'=>""),$id); // TODO: Change the autogenerated stub
    }

    /**
     * override
     * @param $conditions
     * @return bool|int
     */
    public function deletes($conditions)
    {
        return parent::updates(array('del_status' => 1,'sesseion_id'=>""),$conditions); // TODO: Change the autogenerated stub
    }

    /**
     * @param $conditions
     * @return bool|int
     */
    public function realDeletes($conditions){
        return parent::deletes($conditions);
    }


    /***********************下面的是内部调用的 API 方法***********************************************/
    /**
     * 返回某段时间的注册用户数，如果不传参数则返回所有的会员
     * @param $start
     * @param $end
     * @return array|mixed
     */
    public function getTotal($start,$end){
        if($start){
            //$start = "1970-01-01 00:00:00";
			$condition['reg_time']['>'] = $start;
        }
        if($end){
            //$end = "2099-01-01 00:00:00";
			$condition['reg_time']['<='] = $end;
        }
        $condition['del_status'] = 0;
        $item = $this  ->getItems($condition,"count(*) as `total`","","","","");
        return $item[0]['total'];
    }

    /**
     * 根据手机号码，返回用户ID
     * @param $mobile
     * @return mixed
     */
    public function getIdByMobile($mobile){

        return $this -> getItem(array('username' => $mobile,'del_status'=>0),"id,username","");
    }

    /**
     * 根据用户ID，返回手机号码
     * @param $id
     * @return mixed
     */
    public function getUsernameById($id){

        return $this -> getItem(array('id' => $id),"id,username,nickname","");
    }

    /**
     * 根据用户ID获取SaaS中心对应的企业信息，如果没有认证，返回false
     * @param $id
     * @param string $fields
     * @return bool | mixed
     */
    public function getCompanyById( $id, $fields = "userid,company" ){
        if( !$id )return false;
        $item = parent::getItem(array('id'=>$id),"id,dasu_pay_id",null);
        if( !$item['dasu_pay_id'] ){
            //return false;
            return false;//"dasu_pay_id not found";
        }
        $url = 'api/user/getCompanyInfo';
        $result = PayApiClient::send($url,array('userid'=>$item['dasu_pay_id'],'fields'=>$fields));
        if( $result -> isSucess() ){
            return $result -> getItem();
        }else{
            return false;//"POST error"
        }
    }

    /**
     * 根据appid去saas获取对应的企业信息
     * @param $appid
     * @return bool|array
     */
    public function getCompanyByAppId( $appid, $fields='*' ){
        if( !$appid )return false;
        $url = 'api/user/getCompanyByAppId';
        $result = PayApiClient::send($url,array('appid'=>$appid,"fields"=>$fields));
        if( $result -> isSucess() ){
            return $result -> getItem();
        }else{
            return false;
        }
    }

    /**
     * 根据appid去saas获取对应的用户信息
     * @param $appid
     * @return bool|array
     */
    public function getUserByAppId( $appid, $fields='*' ){
        if( !$appid )return false;
        $url = 'api/user/getUserByAppId';
        $result = PayApiClient::send($url,array('appid'=>$appid,"fields"=>$fields));
        if( $result -> isSucess() ){
            return $result -> getItem();
        }else{
            return false;
        }
    }


    /****************下面的是SaaS调用的 API 方法***************************************************************/

    /**
     * SaaS获取终端会员信息方法，已经过滤删除状态
     * @param $conditions
     * @param $fields
     * @param $order
     * @param $limit
     * @param $group
     * @param $having
     * @return array|mixed
     */
    public function getMembers($conditions, $fields, $order, $limit, $group, $having)
    {
        $conditions['del_status'] = 0;
        $this->modelDao->disableAppFilter();
        $rs = parent::getItems($conditions, $fields, $order, $limit, $group, $having);
        $this->modelDao->enableAppFilter();
        return $rs;
    }

    /**
     * 没有增加AppId的计算总数
     * @param $conditions
     * @return mixed
     */
    public function getTotalWithOutAppId( $conditions ){
        $conditions['del_status'] = 0;
        $this->modelDao->disableAppFilter();
        $rs = parent::count($conditions);
        $this->modelDao->enableAppFilter();
        return $rs;
    }

    /**
     * SaaS批量更新信息，只判断dasu_pay_id，不判断APP_ID
     * @param $data
     * @param $conditions
     * @return mixed
     */
    public function updatesWithOutAppId( $data, $conditions ){
        $this->modelDao->disableAppFilter();
        $rs = parent::updates($data,$conditions);
        $this->modelDao->enableAppFilter();
        return $rs;
    }

    /**
     * SaaS获取用户的登陆session_id,用于更新接口session
     * @param $conditions
     * @return bool|mixed
     */
    public function getSessionWithOutAppId($conditions){
        $this->modelDao->disableAppFilter();
        $rs = parent::getItems($conditions,"session_id");
        $this->modelDao->enableAppFilter();
        return $rs;
    }


}
